// TimeService.cpp
#include "TimeService.h"

TimeService::TimeService() 
    : timeClient(ntpUDP, "pool.ntp.org", 60 * 60 * 8, 60000) {}

void TimeService::begin() {
    timeClient.begin();
    timeClient.forceUpdate();
    updateDate();
    lastUpdate = millis();
}

void TimeService::update() {
    timeClient.update();
    
    if (millis() - lastUpdate >= 60000) {
        updateDate();
        lastUpdate = millis();
    }
}

void TimeService::updateDate() {
    unsigned long epochTime = timeClient.getEpochTime();
    time_t rawTime = (time_t)epochTime;
    struct tm *ptm = localtime(&rawTime);
    
    if (ptm) {
        currentDate.year = ptm->tm_year + 1900;
        currentDate.month = ptm->tm_mon + 1;
        currentDate.day = ptm->tm_mday;
        currentDate.dayOfWeek = ptm->tm_wday; // 0=周日, 1=周一, ..., 6=周六
    }
}

uint8_t TimeService::getHours() { 
    return timeClient.getHours(); 
}

uint8_t TimeService::getMinutes() { 
    return timeClient.getMinutes(); 
}

uint8_t TimeService::getSeconds() { 
    return timeClient.getSeconds(); 
}

uint8_t TimeService::getDayOfWeek() {
    return timeClient.getDay(); // 返回0-6，0=周日
}

TimeService::Date TimeService::getDate() { 
    return currentDate; 
}